package com.gpstracker.activities;


import java.util.List;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.gpstracker.R;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.gpstracker.overlays.MyItemizedOverlay;
import com.gpstracker.services.DeleteService;
import com.gpstracker.services.GpsReceiverService;
import com.gpstracker.services.OneShootSybwayService;
import com.gpstracker.services.OverlayHandler;
import com.gpstracker.services.RegistrationService;
import com.gpstracker.services.UpdateUserService;
import com.gpstracker.services.UploadDataService;

@SuppressLint("NewApi")
public class MainActivity extends MapActivity {
	private static final String TAG = "MAIN ACTIVITY";

	private Button start;
	private Button stop;
	private MapView mapView;
	private MapController mapController;
	private MyLocationOverlay myLocationOverlay;
	private List<Overlay> mapOverlays;
	private MyItemizedOverlay itemizedOverlay;
	private Drawable drawable;
	private OverlayHandler overlayHandler;
	private ProgressDialog progressDialog;
	private RadioGroup radiogroup;
	private SharedPreferences sharedPreferences;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mapView = (MapView) findViewById(R.id.mapview);

		mapView.setBuiltInZoomControls(true);

		mapController = mapView.getController();

		mapOverlays = mapView.getOverlays();

		start = (Button) findViewById(R.id.repeatingAlarmbutton);
		stop = (Button) findViewById(R.id.stopAlarmbutton);
		//stop.setClickable(false);
		stop.setEnabled(false);

		sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		setRadioGroup();


		drawable = this.getResources().getDrawable(R.drawable.redpoint);

		mapView.postInvalidate();

	}

	@Override
	protected void onStart() {
		super.onStart();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(mapView.getOverlays().contains(myLocationOverlay))
			myLocationOverlay.enableMyLocation();

		IntentFilter intentToReceiveFilter = new IntentFilter();
		intentToReceiveFilter.addAction(UploadDataService.CUSTOM_INTENT_START);
		intentToReceiveFilter.addAction(UploadDataService.CUSTOM_INTENT_COMPLETE);
		intentToReceiveFilter.addAction(UploadDataService.CUSTOM_INTENT_ERROR);
		this.registerReceiver(mIntentReceiver, intentToReceiveFilter, null, mHandler);
		mReceiversRegistered = true;

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if(mapView.getOverlays().contains(myLocationOverlay))
			myLocationOverlay.disableMyLocation();

		if(mReceiversRegistered) {
			unregisterReceiver(mIntentReceiver);
			mReceiversRegistered = false;
		}

	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_main, menu);
		return true;
	}



//	public void startGettingPosition(char c) {
//		// We cancel alarms that matches with pending intent
//
//		Log.i(TAG, "start service");
//		Toast.makeText(this, "STARTED", Toast.LENGTH_SHORT).show();
//		Intent intent = new Intent(this,GpsReceiverService.class);
//		intent.putExtra("com.gpstracker.PROVIDER_TYPE", c);
//		startService(intent);
//
//		start.setEnabled(false);
//		stop.setEnabled(true);
//	}
	
	public void startGettingPosition(View view) {
		// We cancel alarms that matches with pending intent

		Log.i(TAG, "start service");
		Toast.makeText(this, "STARTED", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(this,GpsReceiverService.class);
		startService(intent);

		start.setEnabled(false);
		stop.setEnabled(true);
	}
	
	

	public void stopGettingPosition(View v) {
		// We cancel alarms that matches with pending intent

		Log.i(TAG, "stop service");
		Toast.makeText(this, "STOPPED", Toast.LENGTH_SHORT).show();
		stopService(new Intent(this, GpsReceiverService.class));

		start.setEnabled(true);
		stop.setEnabled(false);
	}

	public void deleteAllRows(MenuItem menu){
		Log.i(TAG, "deleteAllrows");
		startService(new Intent(this, DeleteService.class));
		itemizedOverlay.clear();
		mapView.postInvalidate();
	}

	public void switchMyLocation(MenuItem menuItem){
		char t = menuItem.getTitle().charAt(0);
		switch (t) {
		case 'E': 
			myLocationOverlay = new MyLocationOverlay(this, mapView);
			mapOverlays.add(myLocationOverlay);
			menuItem.setTitle("Disable my location");
			myLocationOverlay.enableMyLocation();
			myLocationOverlay.runOnFirstFix(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					mapController.animateTo(myLocationOverlay.getMyLocation());
					mapController.setZoom(16);
				}
			});

			break;
		case 'D': 
			myLocationOverlay.disableMyLocation();
			myLocationOverlay = new MyLocationOverlay(this, mapView);
			mapOverlays.remove(myLocationOverlay);
			menuItem.setTitle("Enable my location");
			break;
		default:
			break;
		}
	}

	public void showAll(MenuItem menuItem){
		char t = menuItem.getTitle().charAt(0);
		switch (t) {
		case 'S':
			Log.i(TAG, "showAll");

			itemizedOverlay = new MyItemizedOverlay(drawable, this);
			overlayHandler = new OverlayHandler(itemizedOverlay, getApplicationContext());
			itemizedOverlay.setHandler(overlayHandler);
			overlayHandler.fill();

			mapOverlays.add(itemizedOverlay);
			menuItem.setTitle("Hide all records");
			mapView.postInvalidate();

			break;
		case 'H': 
			if (mapOverlays.contains(itemizedOverlay)){
				mapOverlays.remove(itemizedOverlay);
				menuItem.setTitle("Show all records");
				mapView.postInvalidate();
			}
			break;
		}
	}

	public void info(MenuItem menuItem){
		Log.i("ITEMIZED SIZE: ", String.valueOf(itemizedOverlay.size()));
	}

//	public void showPopupMenu(View v){
//		PopupMenu popupMenu = new PopupMenu(this, v);
//		popupMenu.getMenuInflater().inflate(R.menu.popupmenu, popupMenu.getMenu());
//
//		popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
//
//			@Override
//			public boolean onMenuItemClick(MenuItem item) {
//				Toast.makeText(getApplicationContext(),
//						item.toString(),
//						Toast.LENGTH_LONG).show();
//				char c =  item.getTitle().charAt(0);
//				startGettingPosition(c);
//
//				return true;
//			}
//		});
//
//		popupMenu.show();
//	}

	public void startPreferences(MenuItem menuItem){
		startActivity(new Intent(getApplicationContext(), com.gpstracker.activities.AppPreferencesActivity.class));
	}

	public void userRegistration(MenuItem menuItem){
		Log.i(TAG, "userRegistration");
		startService(new Intent(this, RegistrationService.class));
	}

	public void updateUser(MenuItem menuItem){
		Log.i(TAG, "updateUser");
		startService(new Intent(this, UpdateUserService.class));
	}

	public void uploadLocations(MenuItem menuItem){
		Log.i(TAG, "uploadLocations");
		startService(new Intent(this, UploadDataService.class));
		progressDialog = ProgressDialog.show(this, 
				"", "Working..", true);

	}


	private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(UploadDataService.CUSTOM_INTENT_START)) {
				progressDialog.setProgress(intent.getFlags());
			}
			if(intent.getAction().equals(UploadDataService.CUSTOM_INTENT_COMPLETE)) {
				progressDialog.cancel();
				Toast.makeText(getApplicationContext(), "UPLOADING COMPLETE", Toast.LENGTH_LONG).show();

			}
			if(intent.getAction().equals(UploadDataService.CUSTOM_INTENT_ERROR)){
				progressDialog.cancel();
				Toast.makeText(getApplicationContext(), "YOUR NOT REGISTERED", Toast.LENGTH_LONG).show();
			}
		}

	};

	// Flag if receiver is registered 
	private boolean mReceiversRegistered = false;
	// Define a handler and a broadcast receiver
	private final Handler mHandler = new Handler();

	private void setRadioGroup(){

		radiogroup = (RadioGroup) findViewById(R.id.radioGroup);

		SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("mode", "walk");
        editor.commit();
		
		radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
		{
			public void onCheckedChanged(RadioGroup rGroup, int checkedId)
			{
				// This will get the radiobutton that has changed in its check state
				RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(checkedId);
				// This puts the value (true/false) into the variable
				boolean isChecked = checkedRadioButton.isChecked();
				// If the radiobutton that has changed in check state is now checked...
				if (isChecked)
				{
					// Changes the textview's text to "Checked: example radiobutton text"
					SharedPreferences.Editor editor = sharedPreferences.edit();
					String mode = (String)checkedRadioButton.getText();
					editor.putString("mode", mode);
					editor.commit();
					
//					stopService(new Intent(getApplicationContext(), GpsReceiverService.class));
//					if(mode.equals("subway")){
//						//registra inizio subway
//						startService(new Intent(getApplicationContext(), OneShootSybwayService.class));
//					}
//					else{
//						startService(new Intent(getApplicationContext(), GpsReceiverService.class));
//					}
					
				}
				
			}
		});

	}

}
